package com.ruoyi.bussiness.service.impl;
import com.ruoyi.bussiness.domain.Contant;
import com.ruoyi.bussiness.mapper.ContantMapper;
import com.ruoyi.bussiness.service.ContantService;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.process.domain.workflow.FormDTO;
import com.ruoyi.process.service.IFlowInstance;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 合同信息(Contant)表服务实现类
 *
 * @author makejava
 * @since 2025-07-05 11:59:24
 */
@Service("contantService")
public class ContantServiceImpl extends BaseEntity implements ContantService {
    @Resource
    private  ContantMapper contantMapper;
    @Resource
    private IFlowInstance flowInstance;

    /**
     * 通过ID查询单条数据
     *
     * @param bussinessKey 格式:流程名:id
     * @return 实例对象
     */
    @Override
    public Contant queryById(String  bussinessKey) {
        String[] bussinessKeyArr =  bussinessKey.split(":");
        Long cid = Long.parseLong(bussinessKeyArr[1]);
        return this.contantMapper.queryById(cid);
    }

    /**
     * 分页查询
     *
     * @param contant 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Contant> queryByPage(Contant contant, PageRequest pageRequest) {
        long total = this.contantMapper.count(contant);
        return new PageImpl<>(this.contantMapper.queryAllByLimit(contant, pageRequest), pageRequest, total);
    }


    /**
     * 新增数据
     *
     * @param contant 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Contant insert(Contant contant) {
        //业务数据保存
        this.contantMapper.insert(contant);
        //启动流程 流程类型:id ,如果是租户还加租户号
        String businessKey ="contant："+contant.getCid();
        FormDTO  formDTO = new FormDTO();
        formDTO.setProcessId("flow_myjqgvmc");
        formDTO.setBusinessKey(businessKey);
        formDTO.setFlowVars(new HashMap<>());
        flowInstance.startFlow(formDTO);
        return contant;
    }

    @Override
    public List<Contant> selectContantList(Contant contant) {
        return  this.contantMapper.selectContantList(contant);
    }


    /**
     * 修改数据
     *
     * @param contant 实例对象
     * @return 实例对象
     */
    @Override
    public Contant update(Contant contant) {
        this.contantMapper.update(contant);
        return null;
    }

    /**
     * 通过主键删除数据
     *
     * @param cid 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long cid) {
        return this.contantMapper.deleteById(cid) > 0;
    }
}
